package com.kssoft.ebd.spider.test;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.kssoft.ebd.spider.common.CommonUtils;
import com.kssoft.ebd.spider.common.NullCookiesException;
import com.kssoft.ebd.spider.common.PageModelType;
import com.kssoft.ebd.spider.pool.WebDriverPool;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.io.*;
import java.util.List;
import java.util.Set;

@Component
public class MailQQProcessor implements PageProcessor {
    private static final String BASE_URI = "http://81.cn/yw/";
    private static final String DETAIL = ".+pos=\\d+";
    private static final Site SITE = Site.me().setRetryTimes(3).setSleepTime(100);
    private Set<Cookie> cookies;
    private String targetUrl ="https://mail.qq.com/cgi-bin/readmail?folderid=1&folderkey=1&t=readmail_ad&mailid=ZC0019_NurNcIyMqH0uRmgAI6rccf6&mode=pre&maxage=3600&base=11.129999999999999&ver=19991&sid=-SGx2CRVNeCzEz1V";
    private static final String COOKIE_FILE_PATH = "cookies.ser";
    @Autowired
    private WebDriverPool webDriverPool;
    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        String base_path = "/html/body/table/tbody/tr[2]/td/table/tbody/tr/td[2]/form";
        if (page.getUrl().regex(DETAIL).match()) {
            String content = html.xpath(base_path + "/table[3]/tbody/tr[3]/td").get()/*.replaceAll("<br>", "\r\n")*/;
            String strDate = ReUtil.get("(面试|面谈)时间：(.+?)<br>", content, 2);
            String addr = ReUtil.get("(面试地址|面试地点)：(.+?)<br>", content, 2);
            page.putField("content", content);
        } else {
            List<Selectable> nodes = html.xpath(base_path + "/table[2]/tbody/tr").nodes();
            for (Selectable node : nodes) {
                String subText = node.xpath("//td[6]/p/a/text()").get();
                String subLink = node.xpath("//td[6]/p/a/@href").get();
                if (StrUtil.isBlank(subText)) continue;
                if (subText.contains("面试邀") || subText.contains("面试通知")) {
                    page.addTargetRequest(subLink);
//                    System.err.println(subText);
                }
            }
            String next = html.xpath(base_path + "/table[1]/tbody/tr[3]/td[2]/span[4]/a/@href").get();
            page.addTargetRequest(next);
        }

    }

    @Override
    public Site getSite() {
        try {
            CommonUtils.getCookieToSite(SITE, PageModelType.Home, COOKIE_FILE_PATH);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException | NullCookiesException e) {
            throw new RuntimeException(e);
        }
        return SITE;
    }

    public void start() {
        this.login("https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=102013353&scope=get_user_info%2Cget_app_friends&theme=10&auth_item_state=1&redirect_uri=https%3A%2F%2Fwx.mail.qq.com%2Flist%2Freadtemplate%3Fname%3Dlogin_jump.html%26scene%3D1%26login_type%3Dqq");
        Spider.create(this).addUrl(targetUrl).run();
    }

    public static void main(String[] args) {
        MailQQProcessor processor = new MailQQProcessor();
        processor.start();

    }
    private void login(String url) {

//        WebDriver driver =webDriverPool.getSigle();
        System.setProperty("webdriver.chrome.driver", "D:\\soft\\chromedriver-win64\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get(url);
//            driver.switchTo().frame("ptlogin_iframe");  // 切换到指定
            driver.switchTo().frame(0);
            WebElement switcher_plogin = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("switcher_plogin")));
            switcher_plogin.click();
            WebElement name = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("u")));
            WebElement pwd = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("p")));
            name.sendKeys("785775836");
            pwd.sendKeys("liwu15281807711." + Keys.ENTER);
            // 模拟登录  id  loginsubmit
//            driver.findElement(By.linkText("登录")).click();
            String currentUrl = driver.getCurrentUrl();
//            driver.get(currentUrl);

            driver.switchTo().defaultContent();

            WebElement pwdInput = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("pwdInput")));
            pwdInput.sendKeys("liwu785775836."  + Keys.ENTER);

            ThreadUtil.sleep(5000);

            //点击列表
            driver.switchTo().frame("mainFrame");  // 切换到指定

            WebElement folder_1 = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("folder_1")));
            folder_1.click();


        } finally {
            ThreadUtil.sleep(5000);
            this.cookies = driver.manage().getCookies();
            targetUrl = driver.getCurrentUrl();
            try {
                CommonUtils.saveHomeCookies( cookies);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//            driver.quit();
        }
    }

}
